<template>
  <el-card style="max-width: 480px">
    <template #header>
      <div>
        <span>微商城管理系统</span>
      </div>
    </template>
    <el-form
      label-width="auto"
      :model="formVal"
      :rules="formRules"
      ref="formRef"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          style="width: 240px"
          placeholder="请输入用户名"
          :prefix-icon="User"
          v-model="formVal.userName"
        />
      </el-form-item>
      <el-form-item label="密码" prop="passWord">
        <el-input
          style="width: 240px"
          type="password"
          placeholder="请输入密码"
          show-password
          :prefix-icon="Lock"
          v-model="formVal.passWord"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登 录</el-button>
        <el-button @click="clear">重 置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
  
<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import { Login } from '../api/api';
import { useRouter } from 'vue-router';
import { useTokenStore } from '../store/tokenStore';

const tokenStore = useTokenStore();
const router = useRouter();

const formVal = reactive({
  userName: 'admin',
  passWord: '123'
});
const formRules = reactive({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 8, message: '用户名长度应为3-8个字符', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 12, message: '密码长度应为3-12个字符', trigger: 'blur' }
  ]
});

const formRef = ref(null);

const clear = () => {
  formRef.value.resetFields();
};

const checkLogin = async (formVal) => {
  const resp = await Login(formVal);
  if (resp && resp != null) {
    tokenStore.updateToken(resp.token);
    router.push('/index');
  } else {
    formRef.value.resetFields();
  }
};

const login = () => {
  formRef.value.validate(async (flag) => {
    if (!flag) {
      ElMessage.error('请核对表单数据再提交！！！');
    } else {
      checkLogin(formVal);
    }
  });
};
</script>